# _*_ encoding:utf-8 _*_
"""
定义首页index.html静态化函数
"""
import os

from django.template import loader
from django.conf import settings

from .utils import get_categories
from .models import Content, ContentCategory


def generate_static_index_html():

    # 1. 构建模板参数
    categories = get_categories()  # 获取首页频道的分类导航信息模板参数
    contents = {}  # 获取首页广告模板参数

    # 读取所有的广告 --> 广告位置
    content_categories = ContentCategory.objects.all()
    for content_cat in content_categories:
        # contents['index_lbt'] = [广告对象1， 广告对象2....]
        contents[content_cat.key] = Content.objects.filter(category=content_cat, status=True).order_by('sequence')

    context = {
        'categories': categories,
        'contents': contents
    }

    # 2. 获取模板对象
    template = loader.get_template('index.html')

    # 3. 渲染页面
    html = template.render(context=context)

    static_html_dir = os.path.join(os.path.dirname(os.path.dirname(settings.BASE_DIR)), 'front_end_pc')
    # 4. 保存静态文件
    with open(os.path.join(static_html_dir, 'index.html'), 'w') as f:
        f.write(html)


